<template>
  <div class="import">
    <el-card>
      <h3>员工导入</h3>
      <el-alert
        title="每次导入仅可添加1000名员工，姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
        show-icon
      />
    </el-card>
    <UploadExcel :before-upload="beforeUpload" :on-success="onSuccess" />
  </div>
</template>

<script>
import UploadExcel from '@/components/UploadExcel'
import { importEmployees } from '@/api/employees'
import EMPLOYEECON from '@/api/constant/employees'

function formatDate(numb, format) {
  const time = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return (
    year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
  )
}
// console.log(formatDate(43535))
export default {
  name: 'Import',
  components: {
    UploadExcel
  },

  methods: {
    beforeUpload(file) {
      // console.log(file)
      if (file.size / 1024 / 1024 > 1) {
        this.$message.warning('服务器接受不了这么大的文件！')
        return false
      } else {
        return true
      }
    },
    async onSuccess(data) {
      // console.log(data)

      const _arr = data.results.map((v) => {
        const _obj = {}
        for (const key in v) {
          const currentkey = EMPLOYEECON.excelMap[key]
          // const key=name   v[key]  v.name
          let cirrentValue = v[key]
          if (currentkey === 'timeOfEntry' || currentkey === 'correctionTime') {
            cirrentValue = formatDate(cirrentValue, '/')
          }
          // console.log(cirrentValue)

          _obj[currentkey] = cirrentValue
        }
        return _obj
      })
      // console.log(_arr)
      await importEmployees(_arr)
      // console.log(res)
      this.$message.success('导入成功')
      this.$router.push('/employees')
    }
  }
}
</script>

<style lang="scss">
.import {
  h3 {
    text-align: center;
  }
}
</style>
